<?php
if (!defined('SMF'))
	die('Hacking attempt...');
	
function DOTAStats()
{	
	global $context, $settings, $txt, $scripturl;
	
	$context['dotastats'] = array();
	
	// Load the DOTA Stats language file.
	loadLanguage('DOTAStats');
	
	// Load the DOTA Stats template.
	loadTemplate('DOTAStats');
	
	// Use the DOTA Stats layer.
	$context['template_layers'][] = 'dotastats';
	
	$context['listing_by'] = !empty($_GET['sa']) ? $_GET['sa'] : 'playerlist';
	
	// Setup Button header generation
	$context['sort_links'][] = array(
		'action' => 'playerlist',
		'label' => $txt['dotastats_title_playerlist'],
		'selected' => ($context['listing_by'] == 'playerlist') || ($context['listing_by'] == 'playerdetail'),
	);
	$context['sort_links'][] = array(
		'action' => 'gamelist',
		'label' => $txt['dotastats_title_gamelist'],
		'selected' => ($context['listing_by'] == 'gamelist') || ($context['listing_by'] == 'gamedetail'),
	);
	$context['sort_links'][] = array(
		'action' => 'herolist',
		'label' => $txt['dotastats_title_herolist'],
		'selected' => $context['listing_by'] == 'herolist',
	);
	$context['sort_links'][] = array(
		'action' => 'banlist',
		'label' => $txt['dotastats_title_banlist'],
		'selected' => $context['listing_by'] == 'banlist',
	);
	$context['sort_links'][] = array(
		'action' => 'adminlist',
		'label' => $txt['dotastats_title_adminlist'],
		'selected' => $context['listing_by'] == 'adminlist',
	);
	
	// Add the DOTA Stats stylesheets and scripts.
	$context['html_headers'] .= '
		<link rel="stylesheet" type="text/css" href="' . $settings['default_theme_url'] . '/css/DOTAStats.css" />
		<link rel="stylesheet" type="text/css" href="' . $settings['default_theme_url'] . '/css/dotastats-theme/jquery-ui-1.7.1.custom.css" />
		<script type="text/javascript" src="' . $settings['default_theme_url'] . '/scripts/jquery-1.3.2.min.js"></script>
		<script type="text/javascript" src="' . $settings['default_theme_url'] . '/scripts/jquery-ui-1.7.1.dotastats.min.js"></script>
		<script type="text/javascript" src="' . $settings['default_theme_url'] . '/scripts/jquery.tablesorter.js"></script>
		<script type="text/javascript" src="' . $settings['default_theme_url'] . '/scripts/jquery.gradient.min.js"></script>
		<script type="text/javascript" src="' . $settings['default_theme_url'] . '/scripts/jquery.dimensions.min.js"></script>
		<script type="text/javascript" src="' . $settings['default_theme_url'] . '/scripts/dotastats.js"></script>';
	
	// Update the linktree
	$context['linktree'][] = array (
			'url' => $scripturl . '?action=dotastats',
			'name' => $txt['dotastats_title'],
	);
	
	// Update header info
	UpdateDSHeader();
	
	// Reset result pointer
	$context['dotastats']['start'] = 0;
	
	// Some actions we can do.
	$actions = array(
		'playerlist' => "PlayerList",
		'playerdetail' => "PlayerDetail",
		'gamelist' => "GameList",
		'gamedetail' => "GameDetail",
		'herolist' => "HeroList",
		'banlist' => "BanList",
		'adminlist' => "AdminList",
	);
	
	// Look for a subaction.
	$action = (isset($_REQUEST['sa'])) ? $_REQUEST['sa'] : 'playerlist';
	
	// Make sure it is a valid subaction, otherwise go to the player list.
	if (isset($actions[$action]))
	{
		$context['dotastats']['action'] = $action;
		$actions[$action]();	
	}
	else
	{
		$context['dotastats']['action'] = 'playerlist';
		PlayerList();
	}
}

function UpdateDSHeader()
{
	global $smcFunc, $context;
	
	// Retrieve a count of all ranked players
	$result = $smcFunc['db_query']('', '
		SELECT name, COUNT(dotaplayers.gameid) AS totalgamesplayed
		FROM gameplayers
		LEFT JOIN games ON games.id = gameplayers.gameid 
		LEFT JOIN dotaplayers ON dotaplayers.gameid = games.id AND dotaplayers.colour = gameplayers.colour 
		LEFT JOIN dotagames ON games.id = dotagames.gameid 
		WHERE name IS NOT NULL
		GROUP BY name
		HAVING COUNT(gameplayers.gameid) >= 5
		ORDER BY totalgamesplayed DESC',
		''
	);
	
	$rankedcount = ($smcFunc['db_num_rows']($result) > 0) ? $smcFunc['db_num_rows']($result) : 0;
	
	$i = 0;
	while ($row = $smcFunc['db_fetch_assoc']($result))
	{
		$context['dotastats']['rankedplayers'][$i] = $row['name'];
		$i++;
	}
	$smcFunc['db_free_result']($result);
		
	// Retrieve a count of all players
	$result = $smcFunc['db_query']('', '
		SELECT COUNT(DISTINCT name) as playercount
		FROM gameplayers
		LEFT JOIN dotaplayers ON gameplayers.id = dotaplayers.id AND dotaplayers.colour = gameplayers.colour',
		''
	);
	
	$playerinfo = $smcFunc['db_fetch_assoc']($result);
	$playercount = ($playerinfo) ? $playerinfo['playercount'] : 0;
	$smcFunc['db_free_result']($result);

	// Retrieve game count
	$result = $smcFunc['db_query']('', '
		SELECT COUNT(*) AS totalgames
		FROM dotagames',
		''
	);
	$gamecount = $smcFunc['db_fetch_assoc']($result);
	$gamecount = ($gamecount) ? $gamecount['totalgames'] : 0;
	$smcFunc['db_free_result']($result);
	
	// Retrieve all banned players
	$result = $smcFunc['db_query']('', '
		SELECT COUNT(*) as totalbans
		FROM bans',
		''
	);
	$bancount = $smcFunc['db_fetch_assoc']($result);
	$bancount = ($bancount) ? $bancount['totalbans'] : 0;
	$smcFunc['db_free_result']($result);
	
	// Retrieve all banned players
	$result = $smcFunc['db_query']('', '
		SELECT COUNT(*) as totaladmins
		FROM admins',
		''
	);
	$admincount = $smcFunc['db_fetch_assoc']($result);
	$admincount = ($admincount) ? $admincount['totaladmins'] : 0;
	$smcFunc['db_free_result']($result);
	
	$context['dotastats']['infobar'] = array (
		'rankedplayers' => $rankedcount,
		'totalplayers' => $playercount,
		'totalgames' => $gamecount,
		'totalbans' => $bancount,
		'totaladmins' => $admincount,
	);
}

function PlayerList()
{
	global $context, $scripturl, $txt, $smcFunc;
	
	$context['linktree'][] = array(
			'url' => $scripturl . '?action=dotastats;sa=playerlist',
			'name' => $txt['dotastats_title_playerlist'],
	);
	
	$context['dotastats']['start'] = isset($_REQUEST['start']) ? $_REQUEST['start'] : 0;
	
	if (isset($context['dotastats']['rankedplayers']))
	{
		$rankedplayers = $context['dotastats']['rankedplayers'];
	
		foreach ($rankedplayers as $player)
		{
			$context['dotastats']['players'][$player]['wins'] = 0;
			$context['dotastats']['players'][$player]['losses'] = 0;
			
			// Retrieve game win/loss information for player
			$result = $smcFunc['db_query']('', '
				SELECT winner, newcolour
				FROM gameplayers
				LEFT JOIN games ON games.id = gameplayers.gameid 
				LEFT JOIN dotaplayers ON dotaplayers.gameid = games.id AND dotaplayers.colour = gameplayers.colour 
				LEFT JOIN dotagames ON games.id = dotagames.gameid
				WHERE name = {string:name}
				AND (winner = 1 OR winner = 2)',
				array(
					'name' => $player,
				)
			);
			
			while ($game = $smcFunc['db_fetch_assoc']($result))
			{
				$gameresult = CheckWinLoss($game['newcolour'], $game['winner']);
				if ($gameresult == 'Win')
					$context['dotastats']['players'][$player]['wins']++;
				elseif ($gameresult == 'Loss')
					$context['dotastats']['players'][$player]['losses']++;
			}
			
			$smcFunc['db_free_result']($result);
			
			// Retrieve all DOTA players last game, heroscore and creep score
			$result = $smcFunc['db_query']('', '
				SELECT	MAX(datetime) as lastgamedt, MAX(dotagames.gameid) AS lastgameid,
						MIN(UNIX_TIMESTAMP(datetime)) as firstgameplayed,
						((2 * AVG(kills) + AVG(assists) + 1) / AVG(deaths + 1)) AS heroscore,
						((AVG(creepkills) / 75 + AVG(creepdenies) / 5 + AVG(neutralkills) / 15) / 3) AS creepscore,
						COUNT(dotaplayers.gameid) AS totalgamesplayed
				FROM gameplayers
				LEFT JOIN games ON games.id = gameplayers.gameid 
				LEFT JOIN dotaplayers ON dotaplayers.gameid = games.id AND dotaplayers.colour = gameplayers.colour 
				LEFT JOIN dotagames ON games.id = dotagames.gameid
				WHERE name = {string:name}',
				array(
					'name' => $player,
				)
			);
			
			$playerinfo = $smcFunc['db_fetch_assoc']($result);
			
			$context['dotastats']['players'][$player]['lastgamedt'] = $playerinfo['lastgamedt'];
			$context['dotastats']['players'][$player]['lastgameid'] = $playerinfo['lastgameid'];
			$context['dotastats']['players'][$player]['totalgamesplayed'] = $playerinfo['totalgamesplayed'];
			$context['dotastats']['players'][$player]['gamesperday'] = number(($context['dotastats']['players'][$player]['totalgamesplayed'] / intval((time() - $playerinfo['firstgameplayed']) / 86400)), 2);
			$context['dotastats']['players'][$player]['score'] = ($context['dotastats']['players'][$player]['wins'] + .1) / ($context['dotastats']['players'][$player]['losses'] + .1) + $playerinfo['heroscore'] + $playerinfo['creepscore'];

			$smcFunc['db_free_result']($result);
		}
	}
	
	$context['dotastats']['paging'] = paging_string($context['dotastats']['start'],$context['dotastats']['infobar']['rankedplayers'],25,'dotastats','playerlist');
	
	$context['sub_template'] = 'main';
	$context['page_title'] = $txt['dotastats_title'] . ' - ' . $txt['dotastats_title_playerlist'];
}

function GameList()
{
	global $context, $scripturl, $txt, $smcFunc;
	
	$context['linktree'][] = array(
			'url' => $scripturl . '?action=dotastats;sa=gamelist',
			'name' => $txt['dotastats_title_gamelist'],
	);
	
	$context['dotastats']['start'] = isset($_REQUEST['start']) ? $_REQUEST['start'] : 0;
	
	// Retrieve all DOTA games
	$result = $smcFunc['db_query']('', '
		SELECT  gamename, datetime, dotagames.gameid, COUNT(gameplayers.name) AS playercount, 
				dotagames.min AS minutes, dotagames.sec AS seconds, dotagames.winner
		FROM gameplayers
		LEFT JOIN games ON games.id = gameplayers.gameid 
		LEFT JOIN dotagames ON games.id = dotagames.gameid
		GROUP BY dotagames.gameid
		ORDER BY dotagames.gameid DESC
		LIMIT {int:start},25',
		array(
			'start' => (int) $context['dotastats']['start'],
		)
	);
	
	while ($row = $smcFunc['db_fetch_assoc']($result))
	{
		$context['dotastats']['games'][$row['gameid']] = array(
			'gamename' => $row['gamename'],
			'datetime' => $row['datetime'],
			'playercount' => $row['playercount'],
			'minutes' => $row['minutes'],
			'seconds' => $row['seconds'],
			'winner' => $row['winner'],
		);
	}
	
	$smcFunc['db_free_result']($result);
	
	$context['dotastats']['paging'] = paging_string($context['dotastats']['start'],$context['dotastats']['infobar']['totalgames'],25,'dotastats','gamelist');
	
	$context['sub_template'] = 'main';
	$context['page_title'] = $txt['dotastats_title'] . ' - ' . $txt['dotastats_title_gamelist'];	
}

function GameDetail()
{
	global $context, $scripturl, $txt, $smcFunc, $sourcedir;
	
	require($sourcedir . "/DOTAHeroes.php");
	
	$gameid = (isset($_REQUEST['gameid'])) ? $_REQUEST['gameid'] : '';
	
	$context['linktree'][] = array(
			'url' => $scripturl . '?action=dotastats;sa=gamelist',
			'name' => $txt['dotastats_title_gamelist'],
	);
	$context['linktree'][] = array(
			'url' => $scripturl . '?action=dotastats;gamedetail=' . $gameid,
			'name' => $txt['dotastats_game'] . ' ' . $gameid,
	);
	
	// Retrieve game information
	$result = $smcFunc['db_query']('', '
		SELECT dotagames.gameid, server, map, datetime, gamename, winner, min, sec
		FROM gameplayers
		LEFT JOIN games ON games.id = gameplayers.gameid 
		LEFT JOIN dotaplayers ON dotaplayers.gameid = games.id AND dotaplayers.colour = gameplayers.colour 
		LEFT JOIN dotagames ON games.id = dotagames.gameid
		WHERE dotagames.gameid = {int:gameid}
		GROUP BY dotagames.gameid',
		array(
			'gameid' => (int) $gameid,
		)
	);
	$context['dotastats']['gamedetail'] = $smcFunc['db_fetch_assoc']($result);
	$smcFunc['db_free_result']($result);
	
	// Extract the game version from the map name
	preg_match("/DotA Allstars v(.*)\./", $context['dotastats']['gamedetail']['map'], $matches);
	$context['dotastats']['gamedetail']['version'] = $matches[1];
	
	// Retrieve DOTA game player information
	$result = $smcFunc['db_query']('', '
		SELECT  name, dotaplayers.colour, kills, deaths, creepkills, creepdenies,
				assists, neutralkills, item1, item2, item3, item4, item5, item6, hero, newcolour, towerkills,
				raxkills, courierkills
		FROM gameplayers
		LEFT JOIN games ON games.id = gameplayers.gameid 
		LEFT JOIN dotaplayers ON dotaplayers.gameid = games.id AND dotaplayers.colour = gameplayers.colour 
		LEFT JOIN dotagames ON games.id = dotagames.gameid
		WHERE dotagames.gameid = {int:gameid}
		ORDER BY dotaplayers.newcolour',
		array(
			'gameid' => (int) $gameid,
		)
	);
	
	$i = 0;
	
	$context['dotastats']['gamedetail']['sentinel']['totalkills'] = 0;
	$context['dotastats']['gamedetail']['sentinel']['totaldeaths'] = 0;
	$context['dotastats']['gamedetail']['sentinel']['totalcreepkills'] = 0;
	$context['dotastats']['gamedetail']['sentinel']['totalcreepdenies'] = 0;
	$context['dotastats']['gamedetail']['sentinel']['totalassists'] = 0;
	$context['dotastats']['gamedetail']['sentinel']['totalneutralkills'] = 0;
	$context['dotastats']['gamedetail']['sentinel']['totaltowerkills'] = 0;
	$context['dotastats']['gamedetail']['sentinel']['totalraxkills'] = 0;
	$context['dotastats']['gamedetail']['scourge']['totalkills'] = 0;
	$context['dotastats']['gamedetail']['scourge']['totaldeaths'] = 0;
	$context['dotastats']['gamedetail']['scourge']['totalcreepkills'] = 0;
	$context['dotastats']['gamedetail']['scourge']['totalcreepdenies'] = 0;
	$context['dotastats']['gamedetail']['scourge']['totalassists'] = 0;
	$context['dotastats']['gamedetail']['scourge']['totalneutralkills'] = 0;
	$context['dotastats']['gamedetail']['scourge']['totaltowerkills'] = 0;
	$context['dotastats']['gamedetail']['scourge']['totalraxkills'] = 0;
	
	while ($row = $smcFunc['db_fetch_assoc']($result))
	{
		$context['dotastats']['gamedetail']['players'][$row['newcolour']] = $row;
		
		// Make sure hero name is not null
		$nullcheck = trim($row['hero']);
		if ($nullcheck)
		{
			$context['dotastats']['gamedetail']['players'][$row['newcolour']]['icon'] = $dotaheroes[strtolower($row['hero'])]['icon'];
			$context['dotastats']['gamedetail']['players'][$row['newcolour']]['heroname'] = $dotaheroes[strtolower($row['hero'])]['name'];
			
			// Add to team stat totals
			if ($row['newcolour'] >= 1 && $row['newcolour'] <= 5)
			{
				$context['dotastats']['gamedetail']['sentinel']['totalkills'] += $row['kills'];
				$context['dotastats']['gamedetail']['sentinel']['totaldeaths'] += $row['deaths'];
				$context['dotastats']['gamedetail']['sentinel']['totalcreepkills'] += $row['creepkills'];
				$context['dotastats']['gamedetail']['sentinel']['totalcreepdenies'] += $row['creepdenies'];
				$context['dotastats']['gamedetail']['sentinel']['totalassists'] += $row['assists'];
				$context['dotastats']['gamedetail']['sentinel']['totalneutralkills'] += $row['neutralkills'];
				$context['dotastats']['gamedetail']['sentinel']['totaltowerkills'] += $row['towerkills'];
				$context['dotastats']['gamedetail']['sentinel']['totalraxkills'] += $row['raxkills'];
			}
			else
			{
				$context['dotastats']['gamedetail']['scourge']['totalkills'] += $row['kills'];
				$context['dotastats']['gamedetail']['scourge']['totaldeaths'] += $row['deaths'];
				$context['dotastats']['gamedetail']['scourge']['totalcreepkills'] += $row['creepkills'];
				$context['dotastats']['gamedetail']['scourge']['totalcreepdenies'] += $row['creepdenies'];
				$context['dotastats']['gamedetail']['scourge']['totalassists'] += $row['assists'];
				$context['dotastats']['gamedetail']['scourge']['totalneutralkills'] += $row['neutralkills'];
				$context['dotastats']['gamedetail']['scourge']['totaltowerkills'] += $row['towerkills'];
				$context['dotastats']['gamedetail']['scourge']['totalraxkills'] += $row['raxkills'];
			}
		}
		
		// Check for a banned player
		$nullcheck = trim($row['name']);
		if ($nullcheck)
		{
			$result_ban = $smcFunc['db_query']('', '
				SELECT name, reason
				FROM bans
				WHERE name = {string:name}
				LIMIT 1',
				array(
					'name' => $row['name'],
				)
			);
			
			if ($smcFunc['db_num_rows']($result_ban) > 0)
			{
				$playerban = $smcFunc['db_fetch_assoc']($result_ban);
				$context['dotastats']['gamedetail']['players'][$row['newcolour']]['banned'] = true;
				$context['dotastats']['gamedetail']['players'][$row['newcolour']]['reason'] = $playerban['reason'];
			}
			else
				$context['dotastats']['gamedetail']['players'][$row['newcolour']]['banned'] = false;
			
			$smcFunc['db_free_result']($result_ban);
		}
		$i++;
	}
	$context['dotastats']['gamedetail']['playercount'] = $i;
	
	$smcFunc['db_free_result']($result);
	
	// Only rank stats if this was a complete game
	if ($context['dotastats']['gamedetail']['winner'] == 1 || $context['dotastats']['gamedetail']['winner'] == 2 )
	{
		// Copy player stats to a temporary array for sorting
		$playerstats = $context['dotastats']['gamedetail']['players'];

		// Stats to sort on
		$stats = array('kills','assists','creepdenies','creepkills','neutralkills','towerkills','raxkills');
		
		// Sort on each stat and add markup as appropriate
		foreach ($stats as $stat)
		{
			array_sort($playerstats, '!' . $stat);
			if ($playerstats[0][$stat] != 0)
			{
				$context['dotastats']['gamedetail']['players'][$playerstats[0]['newcolour']][$stat] = '<strong><em>' . $context['dotastats']['gamedetail']['players'][$playerstats[0]['newcolour']][$stat] . '</em></strong>';
				$i = 1;
				while ($playerstats[0][$stat] == $playerstats[$i][$stat])
				{
					$context['dotastats']['gamedetail']['players'][$playerstats[$i]['newcolour']][$stat] = '<strong><em>' . $context['dotastats']['gamedetail']['players'][$playerstats[$i]['newcolour']][$stat] . '</em></strong>';
					$i++;
				}
			}
		}
	}
	$context['sub_template'] = 'main';
	$context['page_title'] = $txt['dotastats_title'] . ' - ' . $txt['dotastats_title_gamelist'];	
}

function PlayerDetail()
{
	global $context, $sourcedir, $scripturl, $txt, $smcFunc, $modSettings;
	
	$player = (isset($_REQUEST['name'])) ? $_REQUEST['name'] : '';
	
	$context['linktree'][] = array(
			'url' => $scripturl . '?action=dotastats;sa=playerlist',
			'name' => $txt['dotastats_title_playerlist'],
	);
	$context['linktree'][] = array(
			'url' => $scripturl . '?action=dotastats;playerdetail=' . $player,
			'name' => $player,
	);
	
	// Check to make sure this is a ranked player
	$result = $smcFunc['db_query']('', '
		SELECT COUNT(dotaplayers.gameid) AS totalgamesplayed
		FROM gameplayers
		LEFT JOIN games ON games.id = gameplayers.gameid 
		LEFT JOIN dotaplayers ON dotaplayers.gameid = games.id AND dotaplayers.colour = gameplayers.colour  
		WHERE name = {string:player}
		HAVING COUNT(gameplayers.gameid) >= 5',
		array(
			'player' => $player,
		)
	);
	
	if ($smcFunc['db_fetch_assoc']($result) && !empty($player))
	{
		$smcFunc['db_free_result']($result);
		
		require($sourcedir . "/DOTAHeroes.php");
	
		$context['dotastats']['playerdetail'] = array();
		
		// Retrieve number of wins for the player
		$result = $smcFunc['db_query']('', '
			SELECT COUNT(winner) AS wins
			FROM gameplayers
			LEFT JOIN games ON games.id = gameplayers.gameid 
			LEFT JOIN dotaplayers ON dotaplayers.gameid = games.id AND dotaplayers.colour = gameplayers.colour 
			LEFT JOIN dotagames ON games.id = dotagames.gameid 
			WHERE name = {string:player}
			AND (
					(
						winner = 1 
						AND dotaplayers.newcolour >= 1
						AND dotaplayers.newcolour <= 5
					) 
					OR
					(
						winner = 2 
						AND dotaplayers.newcolour >= 7 
						AND dotaplayers.newcolour <= 11
					)
				)
			LIMIT 1',
			array(
				'player' => $player,
			)
		);
		$playerinfo = $smcFunc['db_fetch_assoc']($result);
		$smcFunc['db_free_result']($result);
		$context['dotastats']['playerdetail']['wins'] = $playerinfo['wins'];
		
		// Retrieve fastest game time win for the player
		$result = $smcFunc['db_query']('', '
			SELECT dotagames.min * 60 + dotagames.sec AS fastgamewon, dotagames.gameid
			FROM gameplayers
			LEFT JOIN games ON games.id = gameplayers.gameid 
			LEFT JOIN dotaplayers ON dotaplayers.gameid = games.id AND dotaplayers.colour = gameplayers.colour 
			LEFT JOIN dotagames ON games.id = dotagames.gameid 
			WHERE name = {string:player}
			AND (
					(
						winner = 1 
						AND dotaplayers.newcolour >= 1
						AND dotaplayers.newcolour <= 5
					) 
					OR
					(
						winner = 2 
						AND dotaplayers.newcolour >= 7 
						AND dotaplayers.newcolour <= 11
					)
				)
			GROUP BY dotagames.gameid
			ORDER BY fastgamewon ASC
			LIMIT 1',
			array(
				'player' => $player,
			)
		);
		$playerinfo = $smcFunc['db_fetch_assoc']($result);
		$smcFunc['db_free_result']($result);
		$context['dotastats']['playerdetail']['fastgamewon'] = $playerinfo['fastgamewon'];
		$context['dotastats']['playerdetail']['fastgamewonid'] = $playerinfo['gameid'];
		
		// Retrieve longest game time win for the player
		$result = $smcFunc['db_query']('', '
			SELECT (dotagames.min * 60 + dotagames.sec) AS longgamewon, dotagames.gameid
			FROM gameplayers
			LEFT JOIN games ON games.id = gameplayers.gameid 
			LEFT JOIN dotaplayers ON dotaplayers.gameid = games.id AND dotaplayers.colour = gameplayers.colour 
			LEFT JOIN dotagames ON games.id = dotagames.gameid 
			WHERE name = {string:player}
			AND (
					(
						winner = 1 
						AND dotaplayers.newcolour >= 1
						AND dotaplayers.newcolour <= 5
					) 
					OR
					(
						winner = 2 
						AND dotaplayers.newcolour >= 7 
						AND dotaplayers.newcolour <= 11
					)
				)
			GROUP BY dotagames.gameid
			ORDER BY longgamewon DESC
			LIMIT 1',
			array(
				'player' => $player,
			)
		);
		$playerinfo = $smcFunc['db_fetch_assoc']($result);
		$smcFunc['db_free_result']($result);
		$context['dotastats']['playerdetail']['longgamewon'] = $playerinfo['longgamewon'];
		$context['dotastats']['playerdetail']['longgamewonid'] = $playerinfo['gameid'];
		
		// Retrieve fastest game loss, longest game loss and number of losses for the player
		$result = $smcFunc['db_query']('', '
			SELECT COUNT(winner) AS losses
			FROM gameplayers
			LEFT JOIN games ON games.id = gameplayers.gameid 
			LEFT JOIN dotaplayers ON dotaplayers.gameid = games.id AND dotaplayers.colour = gameplayers.colour 
			LEFT JOIN dotagames ON games.id = dotagames.gameid 
			WHERE name = {string:player}
			AND (
					(
						winner = 2 
						AND dotaplayers.newcolour >= 1
						AND dotaplayers.newcolour <= 5
					) 
					OR
					(
						winner = 1 
						AND dotaplayers.newcolour >= 7 
						AND dotaplayers.newcolour <= 11
					)
				)
			LIMIT 1',
			array(
				'player' => $player,
			)
		);
		$playerinfo = $smcFunc['db_fetch_assoc']($result);
		$smcFunc['db_free_result']($result);
		$context['dotastats']['playerdetail']['losses'] = $playerinfo['losses'];
		
		// Retrieve fastest game time loss for the player
		$result = $smcFunc['db_query']('', '
			SELECT dotagames.min * 60 + dotagames.sec AS fastgameloss, dotagames.gameid
			FROM gameplayers
			LEFT JOIN games ON games.id = gameplayers.gameid 
			LEFT JOIN dotaplayers ON dotaplayers.gameid = games.id AND dotaplayers.colour = gameplayers.colour 
			LEFT JOIN dotagames ON games.id = dotagames.gameid 
			WHERE name = {string:player}
			AND (
					(
						winner = 2 
						AND dotaplayers.newcolour >= 1
						AND dotaplayers.newcolour <= 5
					) 
					OR
					(
						winner = 1 
						AND dotaplayers.newcolour >= 7 
						AND dotaplayers.newcolour <= 11
					)
				)
			GROUP BY dotagames.gameid
			ORDER BY fastgameloss ASC
			LIMIT 1',
			array(
				'player' => $player,
			)
		);
		$playerinfo = $smcFunc['db_fetch_assoc']($result);
		$smcFunc['db_free_result']($result);
		$context['dotastats']['playerdetail']['fastgameloss'] = $playerinfo['fastgameloss'];
		$context['dotastats']['playerdetail']['fastgamelossid'] = $playerinfo['gameid'];
		
		// Retrieve fastest game time loss for the player
		$result = $smcFunc['db_query']('', '
			SELECT dotagames.min * 60 + dotagames.sec AS longgameloss, dotagames.gameid
			FROM gameplayers
			LEFT JOIN games ON games.id = gameplayers.gameid 
			LEFT JOIN dotaplayers ON dotaplayers.gameid = games.id AND dotaplayers.colour = gameplayers.colour 
			LEFT JOIN dotagames ON games.id = dotagames.gameid 
			WHERE name = {string:player}
			AND (
					(
						winner = 2 
						AND dotaplayers.newcolour >= 1
						AND dotaplayers.newcolour <= 5
					) 
					OR
					(
						winner = 1 
						AND dotaplayers.newcolour >= 7 
						AND dotaplayers.newcolour <= 11
					)
				)
			GROUP BY dotagames.gameid
			ORDER BY longgameloss DESC
			LIMIT 1',
			array(
				'player' => $player,
			)
		);
		$playerinfo = $smcFunc['db_fetch_assoc']($result);
		$smcFunc['db_free_result']($result);
		$context['dotastats']['playerdetail']['longgameloss'] = $playerinfo['longgameloss'];
		$context['dotastats']['playerdetail']['longgamelossid'] = $playerinfo['gameid'];
		
		// Retrieve a list of all heroes the player has played with some stats.
		$result = $smcFunc['db_query']('', '
			SELECT	hero AS heroid, COUNT(hero) AS timesplayed, (AVG(kills) + AVG(assists) / 2 - AVG(deaths) + 6.5) AS heroscore,
					SUM(kills) AS totalkills, SUM(deaths) AS totaldeaths, SUM(assists) AS totalassists,
					SUM(creepkills) AS totalcreepkills, SUM(creepdenies) AS totalcreepdenies, SUM(neutralkills) AS totalneutralkills,
					SUM(towerkills) AS totaltowerkills, SUM(raxkills) AS totalraxkills, SUM(courierkills) AS totalcourierkills,
					AVG(kills) AS avgkills, AVG(deaths) AS avgdeaths, AVG(assists) AS avgassists,
					AVG(creepkills) AS avgcreepkills, AVG(creepdenies) AS avgcreepdenies, AVG(neutralkills) AS avgneutralkills,
					AVG(towerkills) AS avgtowerkills, AVG(raxkills) AS avgraxkills, AVG(courierkills) AS avgcourierkills
			FROM dotagames
			LEFT JOIN games ON games.id = dotagames.gameid 
			LEFT JOIN gameplayers ON games.id = gameplayers.gameid 
			LEFT JOIN dotaplayers ON dotaplayers.gameid = games.id AND dotaplayers.colour = gameplayers.colour 
			WHERE name = {string:player}
			AND hero IS NOT NULL
			AND hero != ""
			GROUP BY hero',
			array(
				'player' => $player,
			)
		);
		
		$hero_result = array();
		$heroes_merged = array();
		$heroes_unplayed = array();
		
		// Build a temporary array to hold the hero results
		while ($row = $smcFunc['db_fetch_assoc']($result))
		{
			$nullcheck = trim($row['heroid']);
			if ($nullcheck)
				foreach ($row as $key => $value)
				{
					$heroes_result[strtolower($row['heroid'])][strtolower($key)] = strtolower($value);
				}
		}
		
		$smcFunc['db_free_result']($result);
		
		/*
			Build an array of all hero names from DOTAHeroes.php,
			compare this to the players heroes to determine which
			heroes the player has yet to play
		*/
		foreach ($dotaheroes as $hero)
		{
			$heroes_unplayed[$hero['name']] = array (
				'icon' => $hero['icon'],
			);
		}
		
		/*
			Find the hero name for each hero using the $dotaheroes array from DOTAHeroes.php.
			Add all heroes to the dotastats context, merging duplicates based off of the hero 
			name as a unique id
		*/
		foreach ($heroes_result as $key => $values)
		{
			$heroes_result[$key]['name'] = $dotaheroes[$key]['name'];
			$heroes_result[$key]['icon'] = $dotaheroes[$key]['icon'];
			if (array_key_exists($heroes_result[$key]['name'], $heroes_merged))
			{
				$heroes_merged[$heroes_result[$key]['name']]['timesplayed'] += $heroes_result[$key]['timesplayed'];
				$heroes_merged[$heroes_result[$key]['name']]['totalkills'] += $heroes_result[$key]['totalkills'];
				$heroes_merged[$heroes_result[$key]['name']]['totaldeaths'] += $heroes_result[$key]['totaldeaths'];
				$heroes_merged[$heroes_result[$key]['name']]['totalassists'] += $heroes_result[$key]['totalassists'];
				$heroes_merged[$heroes_result[$key]['name']]['totalcreepkills'] += $heroes_result[$key]['totalcreepkills'];
				$heroes_merged[$heroes_result[$key]['name']]['totalcreepdenies'] += $heroes_result[$key]['totalcreepdenies'];
				$heroes_merged[$heroes_result[$key]['name']]['totalneutralkills'] += $heroes_result[$key]['totalneutralkills'];
				$heroes_merged[$heroes_result[$key]['name']]['totaltowerkills'] += $heroes_result[$key]['totaltowerkills'];
				$heroes_merged[$heroes_result[$key]['name']]['totalraxkills'] += $heroes_result[$key]['totalraxkills'];
				$heroes_merged[$heroes_result[$key]['name']]['totalcourierkills'] += $heroes_result[$key]['totalcourierkills'];
				$heroes_merged[$heroes_result[$key]['name']]['avgkills'] = ($heroes_merged[$heroes_result[$key]['name']]['avgkills'] + $heroes_result[$key]['avgkills']) / 2;
				$heroes_merged[$heroes_result[$key]['name']]['avgdeaths'] = ($heroes_merged[$heroes_result[$key]['name']]['avgdeaths'] + $heroes_result[$key]['avgdeaths']) / 2;
				$heroes_merged[$heroes_result[$key]['name']]['avgassists'] = ($heroes_merged[$heroes_result[$key]['name']]['avgassists'] + $heroes_result[$key]['avgassists']) / 2;
				$heroes_merged[$heroes_result[$key]['name']]['avgcreepkills'] = ($heroes_merged[$heroes_result[$key]['name']]['avgcreepkills'] + $heroes_result[$key]['avgcreepkills']) / 2;
				$heroes_merged[$heroes_result[$key]['name']]['avgcreepdenies'] = ($heroes_merged[$heroes_result[$key]['name']]['avgcreepdenies'] + $heroes_result[$key]['avgcreepdenies']) / 2;
				$heroes_merged[$heroes_result[$key]['name']]['avgneutralkills'] = ($heroes_merged[$heroes_result[$key]['name']]['avgneutralkills'] + $heroes_result[$key]['avgneutralkills']) / 2;
				$heroes_merged[$heroes_result[$key]['name']]['avgtowerkills'] = ($heroes_merged[$heroes_result[$key]['name']]['avgtowerkills'] + $heroes_result[$key]['avgtowerkills']) / 2;
				$heroes_merged[$heroes_result[$key]['name']]['avgraxkills'] = ($heroes_merged[$heroes_result[$key]['name']]['avgraxkills'] + $heroes_result[$key]['avgraxkills']) / 2;
				$heroes_merged[$heroes_result[$key]['name']]['avgcourierkills'] = ($heroes_merged[$heroes_result[$key]['name']]['avgcourierkills'] + $heroes_result[$key]['avgcourierkills']) / 2;
			}
			elseif (!empty($heroes_result[$key]['name']))
				$heroes_merged[$heroes_result[$key]['name']] = $heroes_result[$key];
				
			if (array_key_exists($heroes_result[$key]['name'], $heroes_unplayed))
				unset($heroes_unplayed[$heroes_result[$key]['name']]);
		}
		
		// Generate 5 most popular heroes for the player
		array_sort($heroes_merged,'!timesplayed');
		$context['dotastats']['playerdetail']['popularheroes'] = array_slice($heroes_merged, 0, 5);
		
		// Generate 5 most UN-popular heroes for the player
		array_sort($heroes_merged,'timesplayed');
		$context['dotastats']['playerdetail']['unpopularheroes'] = array_slice($heroes_merged, 0, 5);
		
		// Generate 5 best scoring heroes for the player
		array_sort($heroes_merged,'!heroscore');
		$context['dotastats']['playerdetail']['bestheroscores'] = array_slice($heroes_merged, 0, 5);	

		// Generate 5 worst scoring heroes for the player
		array_sort($heroes_merged,'heroscore','!avgdeaths');
		$context['dotastats']['playerdetail']['worstheroscores'] = array_slice($heroes_merged, 0, 5);	
		
		// Add the array to the dotastats context
		$context['dotastats']['playerdetail']['unplayedheroes'] = $heroes_unplayed;
		
		// Retrieve last 5 games played
		$result = $smcFunc['db_query']('', '
			SELECT datetime, dotagames.gameid, hero, kills, deaths, assists, winner, newcolour
			FROM dotagames
			LEFT JOIN games ON games.id = dotagames.gameid 
			LEFT JOIN gameplayers ON games.id = gameplayers.gameid 
			LEFT JOIN dotaplayers ON dotaplayers.gameid = games.id AND dotaplayers.colour = gameplayers.colour 
			WHERE name = {string:player}
			ORDER BY datetime DESC
			LIMIT 5',
			array(
				'player' => $player,
			)
		);
		
		while ($row = $smcFunc['db_fetch_assoc']($result))
		{
			$context['dotastats']['playerdetail']['recentgames'][$row['gameid']] = $row;
			$context['dotastats']['playerdetail']['recentgames'][$row['gameid']]['gamestatus'] = CheckWinLoss($row['newcolour'],$row['winner']);
			$nullcheck = trim($row['hero']);
			if ($nullcheck)
			{
				$context['dotastats']['playerdetail']['recentgames'][$row['gameid']]['icon'] = $dotaheroes[strtolower($row['hero'])]['icon'];
				$context['dotastats']['playerdetail']['recentgames'][$row['gameid']]['title'] = $dotaheroes[strtolower($row['hero'])]['name'];
			}
		}
			
		$smcFunc['db_free_result']($result);
			
		// Retrieve average game length, best loading time, total games played
		$result = $smcFunc['db_query']('', '
			SELECT	AVG(min*60 + sec) AS avggamelength,
					MIN(loadingtime) AS bestloadtime, COUNT(dotaplayers.gameid) as gamesplayed
			FROM dotagames
			LEFT JOIN games ON games.id = dotagames.gameid 
			LEFT JOIN gameplayers ON games.id = gameplayers.gameid 
			LEFT JOIN dotaplayers ON dotaplayers.gameid = games.id AND dotaplayers.colour = gameplayers.colour 
			WHERE name = {string:player}',
			array(
				'player' => $player,
			)
		);
		$playerinfo = $smcFunc['db_fetch_assoc']($result);
		$smcFunc['db_free_result']($result);
		$context['dotastats']['playerdetail']['avggamelength'] = (int) $playerinfo['avggamelength'];
		$context['dotastats']['playerdetail']['bestloadtime'] = number(($playerinfo['bestloadtime'] / 1000), 2);
		$context['dotastats']['playerdetail']['gamesplayed'] = $playerinfo['gamesplayed'];
		
		// Retrieve first game played
		$result = $smcFunc['db_query']('', '
			SELECT datetime AS firstgame, UNIX_TIMESTAMP(datetime) AS fgtimestamp, dotagames.gameid
			FROM dotagames
			LEFT JOIN games ON games.id = dotagames.gameid 
			LEFT JOIN gameplayers ON games.id = gameplayers.gameid 
			LEFT JOIN dotaplayers ON dotaplayers.gameid = games.id AND dotaplayers.colour = gameplayers.colour 
			WHERE name = {string:player}
			ORDER BY datetime ASC
			LIMIT 1',
			array(
				'player' => $player,
			)
		);
		$playerinfo = $smcFunc['db_fetch_assoc']($result);
		$smcFunc['db_free_result']($result);
		$context['dotastats']['playerdetail']['firstgame'] = $playerinfo['firstgame'];
		$context['dotastats']['playerdetail']['firstgameid'] = $playerinfo['gameid'];
		$context['dotastats']['playerdetail']['gamesperday'] = number(($context['dotastats']['playerdetail']['gamesplayed'] / intval((time() - $playerinfo['fgtimestamp']) / 86400)), 2);
		
		// Disable query check due subselects in next query
		$modSettings['disableQueryCheck'] = 1;
		
		// Retrieve detailed player stats
		$result = $smcFunc['db_query']('', '
			SELECT	name, tk.topkills, tk.topkillsgameid, td.topdeaths, td.topdeathsgameid, ta.topassists, ta.topassistsgameid,
					tck.topcreepkills, tck.topcreepkillsgameid, tcd.topcreepdenies, tcd.topcreepdeniesgameid, tnk.topneutralkills, tnk.topneutralkillsgameid,
					ttk.toptowerkills, ttk.toptowerkillsgameid, trk.topraxkills, trk.topraxkillsgameid, tchk.topcourierkills, tchk.topcourierkillsgameid,
					AVG(kills) AS avgkills, AVG(deaths) AS avgdeaths, AVG(assists) AS avgassists,
					AVG(creepkills) AS avgcreepkills, AVG(creepdenies) AS avgcreepdenies, AVG(neutralkills) AS avgneutralkills,
					AVG(towerkills) AS avgtowerkills, AVG(raxkills) AS avgraxkills, AVG(courierkills) AS avgcourierkills,
					SUM(kills) AS totalkills, SUM(deaths) AS totaldeaths, SUM(assists) AS totalassists,
					SUM(creepkills) AS totalcreepkills, SUM(creepdenies) AS totalcreepdenies, SUM(neutralkills) AS totalneutralkills,
					SUM(towerkills) AS totaltowerkills, SUM(raxkills) AS totalraxkills, SUM(courierkills) AS totalcourierkills,
					((2 * AVG(kills) + AVG(assists) + 1) / AVG(deaths + 1)) AS heroscore,
					((AVG(creepkills) / 75 + AVG(creepdenies) / 5 + AVG(neutralkills) / 15) / 3) AS creepscore
			FROM dotaplayers
			LEFT JOIN gameplayers ON dotaplayers.gameid = gameplayers.gameid AND dotaplayers.colour = gameplayers.colour
			JOIN
				(
					SELECT kills AS topkills, dotaplayers.gameid AS topkillsgameid
					FROM dotaplayers
					LEFT JOIN gameplayers ON dotaplayers.gameid = gameplayers.gameid AND dotaplayers.colour = gameplayers.colour
					WHERE name = {string:player}
					ORDER BY kills DESC
					LIMIT 1
				) AS tk ON dotaplayers.gameid = gameplayers.gameid AND dotaplayers.colour = gameplayers.colour
			JOIN
				(
					SELECT deaths AS topdeaths, dotaplayers.gameid AS topdeathsgameid
					FROM dotaplayers
					LEFT JOIN gameplayers ON dotaplayers.gameid = gameplayers.gameid AND dotaplayers.colour = gameplayers.colour
					WHERE name = {string:player}
					ORDER BY deaths DESC
					LIMIT 1
				) AS td ON dotaplayers.gameid = gameplayers.gameid AND dotaplayers.colour = gameplayers.colour
			JOIN 
				(
					SELECT assists AS topassists, dotaplayers.gameid AS topassistsgameid
					FROM dotaplayers
					LEFT JOIN gameplayers ON dotaplayers.gameid = gameplayers.gameid AND dotaplayers.colour = gameplayers.colour
					WHERE name = {string:player}
					ORDER BY assists DESC
					LIMIT 1
				) AS ta ON dotaplayers.gameid = gameplayers.gameid AND dotaplayers.colour = gameplayers.colour
			JOIN
				(
					SELECT creepkills AS topcreepkills, dotaplayers.gameid AS topcreepkillsgameid
					FROM dotaplayers
					LEFT JOIN gameplayers ON dotaplayers.gameid = gameplayers.gameid AND dotaplayers.colour = gameplayers.colour
					WHERE name = {string:player}
					ORDER BY creepkills DESC
					LIMIT 1
				) AS tck ON dotaplayers.gameid = gameplayers.gameid AND dotaplayers.colour = gameplayers.colour
			JOIN 
				(
					SELECT creepdenies AS topcreepdenies, dotaplayers.gameid AS topcreepdeniesgameid
					FROM dotaplayers
					LEFT JOIN gameplayers ON dotaplayers.gameid = gameplayers.gameid AND dotaplayers.colour = gameplayers.colour
					WHERE name = {string:player}
					ORDER BY creepdenies DESC
					LIMIT 1
				) AS tcd ON dotaplayers.gameid = gameplayers.gameid AND dotaplayers.colour = gameplayers.colour
			JOIN 
				(
					SELECT neutralkills AS topneutralkills, dotaplayers.gameid AS topneutralkillsgameid
					FROM dotaplayers
					LEFT JOIN gameplayers ON dotaplayers.gameid = gameplayers.gameid AND dotaplayers.colour = gameplayers.colour
					WHERE name = {string:player}
					ORDER BY neutralkills DESC
					LIMIT 1
				) AS tnk ON dotaplayers.gameid = gameplayers.gameid AND dotaplayers.colour = gameplayers.colour
			JOIN 
				(
					SELECT towerkills AS toptowerkills, dotaplayers.gameid AS toptowerkillsgameid
					FROM dotaplayers
					LEFT JOIN gameplayers ON dotaplayers.gameid = gameplayers.gameid AND dotaplayers.colour = gameplayers.colour
					WHERE name = {string:player}
					ORDER BY towerkills DESC
					LIMIT 1
				) AS ttk ON dotaplayers.gameid = gameplayers.gameid AND dotaplayers.colour = gameplayers.colour
			JOIN 
				(
					SELECT raxkills AS topraxkills, dotaplayers.gameid AS topraxkillsgameid
					FROM dotaplayers
					LEFT JOIN gameplayers ON dotaplayers.gameid = gameplayers.gameid AND dotaplayers.colour = gameplayers.colour
					WHERE name = {string:player}
					ORDER BY raxkills DESC
					LIMIT 1
				) AS trk ON dotaplayers.gameid = gameplayers.gameid AND dotaplayers.colour = gameplayers.colour
			JOIN 
				(
					SELECT courierkills AS topcourierkills, dotaplayers.gameid AS topcourierkillsgameid
					FROM dotaplayers
					LEFT JOIN gameplayers ON dotaplayers.gameid = gameplayers.gameid AND dotaplayers.colour = gameplayers.colour
					WHERE name = {string:player}
					ORDER BY courierkills DESC
					LIMIT 1
				) AS tchk ON dotaplayers.gameid = gameplayers.gameid AND dotaplayers.colour = gameplayers.colour
			WHERE name = {string:player}
			LIMIT 1',
			array(
				'player' => $player,
			)
		);
		
		$playerinfo = $smcFunc['db_fetch_assoc']($result);
		$smcFunc['db_free_result']($result);
		
		$modSettings['disableQueryCheck'] = 0;
		
		foreach ($playerinfo as $key => $value)
			$context['dotastats']['playerdetail'][$key] = $value;
		
		// Calculate the player win/loss score
		$context['dotastats']['playerdetail']['winlossscore'] = ($context['dotastats']['playerdetail']['wins'] + .1) / ($context['dotastats']['playerdetail']['losses'] + .1);
		
		// Calculate the players total score
		$context['dotastats']['playerdetail']['score'] = $context['dotastats']['playerdetail']['winlossscore'] + $context['dotastats']['playerdetail']['heroscore'] + $context['dotastats']['playerdetail']['creepscore'];
	}
	else
		$context['dotastats']['playerdetail'] = false;
	
	$context['sub_template'] = 'main';
	$context['page_title'] = $txt['dotastats_title'] . ' - ' . $txt['dotastats_title_gamelist'] . ' - ' . $player;
}

function HeroList()
{
	global $context, $scripturl, $txt, $smcFunc;
	
	$context['linktree'][] = array(
			'url' => $scripturl . '?action=dotastats;sa=herolist',
			'name' => $txt['dotastats_title_herolist'],
	);

	$context['sub_template'] = 'main';
	$context['page_title'] = $txt['dotastats_title'] . ' - ' . $txt['dotastats_title_herolist'];	
}

function BanList()
{
	global $context, $scripturl, $txt, $smcFunc;

	$context['linktree'][] = array(
			'url' => $scripturl . '?action=dotastats;sa=banlist',
			'name' => $txt['dotastats_title_banlist'],
	);
	
	$context['dotastats']['start'] = isset($_REQUEST['start']) ? $_REQUEST['start'] : 0;
	
	// Retrieve all banned players
	$result = $smcFunc['db_query']('', '
		SELECT *
		FROM bans
		ORDER BY date DESC
		LIMIT {int:start},25',
		array(
			'start' => (int) $context['dotastats']['start'],
		)
	);
	
	while ($row = $smcFunc['db_fetch_assoc']($result))
	{
		$context['dotastats']['bans'][$row['id']] = array(
			'server' => substr($row['server'],0,-11),
			'name' => $row['name'],
			'ip' => $row['ip'],
			'date' => $row['date'],
			'gamename' => $row['gamename'],
			'admin' => $row['admin'],
			'reason' => $row['reason'],
		);
	}
	
	$smcFunc['db_free_result']($result);
	
	$context['dotastats']['paging'] = paging_string($context['dotastats']['start'],$context['dotastats']['infobar']['totalbans'],25,'dotastats','banlist');
	
	$context['sub_template'] = 'main';
	$context['page_title'] = $txt['dotastats_title'] . ' - ' . $txt['dotastats_title_banlist'];
}

function AdminList()
{
	global $context, $scripturl, $txt, $smcFunc;

	$context['linktree'][] = array(
			'url' => $scripturl . '?action=dotastats;sa=gamelist',
			'name' => $txt['dotastats_title_adminlist'],
	);

	$context['sub_template'] = 'main';
	$context['page_title'] = $txt['dotastats_title'] . ' - ' . $txt['dotastats_title_adminlist'];
}


// Paging string generation
function paging_string($start,$total,$limit,$action,$subaction)
{
	$paging_string = '<strong>';
						
	// Don't display the right arrows if we are at the beginning of the results
	if ($start != 0) 
	{
		$paging_string .= '<a class="" href="?action=' . $action . ';sa=' . $subaction . ';start=0"><<</a> <a class="" href="?action=' . $action . ';sa=' . $subaction . ';start=';
		
		/*
			Output will look like this: << "<" x - y out of z > >>
			Figure out how to go back $limit results
		*/
		if (($start - $limit) < 0)
			$paging_string .= '0';
		else
			$paging_string .= $start - $limit;

		$paging_string .= '"><';
	}
	
	$paging_string .= '</a>  ' . ($start + 1) . ' - ';
		
	/*
		Output will look like this: << < x - "y" out of z > >>
		If we are near the end of the results, we need to display the correct ending number
	*/
	if (($start + $limit) > $total)
		$paging_string .= ($start + ($total - $start));
	else
		$paging_string .= ($start + $limit);
	
	$paging_string .= ' of ' . $total;
		
	// Skip arrow display if at end of result
	if (($start + $limit + 1) < $total)
	{
		$paging_string .= '<a class="" href="?action=' . $action . ';sa=' . $subaction . ';start=';
	
		/*
			Output will look like this: << < x - y out of z ">" >>
			Make sure we don't go over the max characters for the next result
		*/
		if ($start + $limit + 1 > $total)
		{
			$start = $total;
			while (($start % $limit) != 0)
				$start--;
			
			$paging_string .= $start;
		}
		else
			$paging_string .= $start + $limit;
		
		$paging_string .= '"> ></a> <a class="" href="?action=' . $action . ';sa=' . $subaction . ';start=';
								
		/*
			Output will look like this: << < x - y out of z > ">>"
			Figure out how to get the very end of our results with going over
		*/
		if ($total < $limit)
			$paging_string .= '0';
		elseif (($total % $limit) != 0)
		{
			$start = $total;
			while (($start % $limit) != 0)
				$start--;

			$paging_string .= $start;
		}
		else
			$paging_string .= $total - $limit;
		
		$paging_string .= '">>></a>';
	}
	
	$paging_string .= '</strong>';
	
	return $paging_string;
}

// Return green/red/grey depending on win/loss
function WinLossColor($winner, $side)
{
	if ($winner == $side)
		return 'B1CDB3';  // green
	elseif ($winner != $side && ($winner == 1 || $winner == 2))
		return 'BFACAC';  // red
	else
		return 'CCCCCC';  // grey
}

// Check for win loss depending on player color in the game
function CheckWinLoss($color, $winner)
{
	global $txt;
	
	if (($winner == 2 && $color >= 1 && $color <= 5) || ($winner == 1 && $color >= 7 && $color <= 11))
		return $txt['dotastats_loss'];
	elseif (($winner == 1 && $color >= 1 && $color <= 5) || ($winner == 2 && $color >= 7 && $color <= 11))
		return $txt['dotastats_win'];
	else
		return $txt['dotastats_incomplete'];
}

/*
	Multi-dimensional array sort functions
	Derived from http://ca3.php.net/manual/en/function.array-multisort.php#90541
*/
function array_sort_func($a,$b=NULL) { 
   static $keys; 
   if ($b===NULL) return $keys=$a; 
   foreach ($keys as $k) { 
      if (@$k[0]=='!') { 
         $k=substr($k,1); 
         if (@$a[$k]!==@$b[$k]) { 
            return strnatcmp(@$b[$k],@$a[$k]); 
         } 
      } 
      else if(@$a[$k]!==@$b[$k]) { 
         return strnatcmp(@$a[$k],@$b[$k]); 
      } 
   } 
   return 0; 
} 

function array_sort(&$array) { 
   if (!$array) return $keys; 
   $keys=func_get_args(); 
   array_shift($keys); 
   array_sort_func($keys); 
   usort($array,"array_sort_func");        
} 



?>